import React, { memo, useState, useEffect } from "react";
import { Upload, message } from "antd";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import OSS from "ali-oss";
import moment from "moment";

// function getBase64(img, callback) {
//   const reader = new FileReader();
//   reader.addEventListener("load", () => callback(reader.result));
//   reader.readAsDataURL(img);
// }

const uploadPath = (path, file) => {
  // 上传在阿里云的文件路径文件的路径，使用日期命名文件目录
  return `${moment().format("YYYYMMDD")}/${file.name.split(".")[0]}-${
    file.uid
  }.${file.type.split("/")[1]}`;
};

export default memo(function Uploadyzh(props) {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState("");
  useEffect(() => {
    if (props.imgurl) {
      setImageUrl(props.imgurl);
    }
  }, [props]);
  const { setimg } = props;
  //imgurl改变并回传
  useEffect(() => {
    setimg(imageUrl);
  }, [imageUrl, setimg]);

  const UploadToOss = (path, file) => {
    const url = uploadPath(path, file);
    return new Promise((resolve, reject) => {
      client()
        .multipartUpload(url, file)
        .then((data) => {
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  };
  const client = () => {
    return new OSS({
      region: "oss-cn-beijing", //oss所在region，由运维提供
      accessKeyId: "LTAI5t6R7ZqjbUXRCyQLMv4p", //oss的子accessKeyId,由运维提供
      accessKeySecret: "fBgWfl4X1yieM0CsJoag6sBJYiIybA", //oss的子accessKeySecret,由运维提供
      bucket: "javawebimg1", //oss的buket名称，运维提供
    });
  };

  function beforeUpload(file) {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
      return;
    }
    console.log(file);
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {
      // 使用ossupload覆盖默认的上传方法
      UploadToOss("yzh", file)
        .then((data) => {
          setLoading(false);
          setImageUrl(
            data.res.requestUrls[0].slice(
              0,
              data.res.requestUrls[0].indexOf("?") !== -1
                ? data.res.requestUrls[0].indexOf("?")
                : data.res.requestUrls[0].length
            )
          );
          return data;
        })
        .catch((error) => {
          console.log(error);
        });
    };
    return isJpgOrPng && isLt2M;
  }
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  return (
    <div>
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        beforeUpload={beforeUpload}
      >
        {imageUrl ? (
          <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
        ) : (
          uploadButton
        )}
      </Upload>
    </div>
  );
});
